package com.model.common.base.basic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.multidex.MultiDexApplication;

import com.model.common.utils.http.RetrofitHelper;
import com.model.common.utils.http.back.LogInterceptor;
import com.model.common.utils.http.call.CompletableCallAdapterFactory;
import com.model.common.utils.http.call.ReplaceUrlCallFactory;
import com.model.common.utils.http.converter.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

/**
 * Create by Carson on 2021/12/23.
 * BaseApplication
 */
public class BaseApplication extends MultiDexApplication {

    @SuppressLint("StaticFieldLeak")
    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        //初始化网络请求
        initHttp();
    }

    /**
     * 初始化网络请求
     */
    private void initHttp() {
        LogInterceptor logInterceptor = new LogInterceptor(message -> {
            Log.e("httpMessage", message);
        });
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(logInterceptor)
                .connectTimeout(6L, TimeUnit.SECONDS)
                .readTimeout(6L, TimeUnit.SECONDS)
                .build();
        RetrofitHelper.DEFAULT = new Retrofit.Builder()
                .baseUrl(Constants.Urls.BASE_URL)
                .callFactory(new ReplaceUrlCallFactory(client) {
                    @Nullable
                    @Override
                    protected HttpUrl getNewUrl(String baseUrlName, Request request) {
                        String oldUrl = request.url().toString();
                        if (baseUrlName.equals("city")) {
                            String newUrl = oldUrl.replace(Constants.Urls.BASE_URL,
                                    "https://staticyx.lnetco.com/");
                            return HttpUrl.get(newUrl);
                        }
                        return null;
                    }
                })
                .addCallAdapterFactory(CompletableCallAdapterFactory.INSTANCE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
